from google.appengine.ext import webapp
register = webapp.template.create_template_register()

def truncate(value, size):
  return value[0:size]

def truncate_dot(value, size):
  if len(value) > size and size > 3:
    return value[0:(size-3)] + '...'
  else:
    return value[0:size]
  
def multiply(value, default_value):
  if value:
    return int(float(value) * 100)
  else:
    return int(float(default_value) * 100)

def commas(value):
  """Formats an integer with thousands-separating commas.

  Args:
    value: An integer.

  Returns:
    A string.
  """
  try:
    value = int(value)
  except:
    value = 0

  if value < 0:
    sign = '-'
    value = -value
  else:
    sign = ''
  result = []
  while value >= 1000:
    result.append('%03d' % (value % 1000))
    value /= 1000
  result.append('%d' % value)
  return sign + ','.join(reversed(result))

register.filter(truncate_dot)
register.filter(truncate)
register.filter(multiply)
register.filter(commas)
